package com.example.safeassistan.home.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.safeassistan.R;
import com.example.safeassistan.UserInfoModel;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.base.BaseModel;
import com.example.safeassistan.common.UserData;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.hiddendanger.activity.HiddendangerUnSubmit;
import com.example.safeassistan.hiddendanger.model.HiddenDangerDetailModel;
import com.example.safeassistan.home.fragment.RiskDetailBasicInfoFragment;
import com.example.safeassistan.home.fragment.RiskDetailCheckLogFragment;
import com.example.safeassistan.home.fragment.RiskDetailHiddendangerFragment;
import com.example.safeassistan.home.fragment.RiskDetailInstructionFragment;
import com.example.safeassistan.home.fragment.RiskDetailPersonFragment;
import com.example.safeassistan.home.fragment.RiskDetailRiskFragment;
import com.example.safeassistan.home.fragment.RiskDetailTableFragment;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.risk.model.RiskPointDetailModel;
import com.example.safeassistan.utile.GlideEngine;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.utile.PictureUtils;
import com.example.safeassistan.utile.ToastUtil;
import com.example.safeassistan.widget.BounceScrollView;
import com.example.safeassistan.widget.PhotoPickBottomDialog;
import com.example.safeassistan.widget.ViewPagerForScrollView;
import com.google.android.material.tabs.TabLayout;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RiskPointDetail extends BaseActivity implements View.OnClickListener {
    private TabLayout tabLayout;
    private ImageView _barBack;
    private TextView _barTvRight;
    private TextView tvRegisterHiddenDanger;
    private ViewPagerForScrollView viewPager;
    private TextView tvWarnning;
    private LinearLayout llWarnning;
    private List<Fragment> fragmentList;
    private List<String> mTitleList;
    private BounceScrollView scrollView;
    private MainAdapter adapter;
    private TextView tvImmediateCheck,tvMore;
    private ImageView ivCamera;
    private TextView tvRiskPointTitle,tvDepartName;
    private RiskPointDetailModel riskPointDetail;
    private ImageView ivLevel,ivStatus,ivRiskPoint;
    private int riskLevel=0;

    private String riskpointId="";

    private String checkStatus="";

    public static void actionStart(Context context,String riskpointId,int riskLevel,String checkStatus ) {
        Intent intent = new Intent(context, RiskPointDetail.class);
        intent.putExtra("riskpointId",riskpointId);
        intent.putExtra("riskLevel",riskLevel);
        intent.putExtra("checkStatus",checkStatus);
        context.startActivity(intent);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id._barBack:
                finish();
                break;
            case R.id._barTvRight:
                //回到顶部
                scrollView.fullScroll(ScrollView.FOCUS_UP);
                break;
            case R.id.tvImmediateCheck:
                //立即巡检
                if (UserData.create(RiskPointDetail.this).get(UserData.ls_xj).equals("0")){
                    ActivitySafeTable.actionStart(0,RiskPointDetail.this,riskpointId,riskPointDetail.getResult().getRiskPointName(),"");
                }else {
                    RiskPointDetailImmediatelyPatrol.actionStart(getContext(),riskpointId);
                }
                break;
            case R.id.tvMore:
                //查看更多告警列表
                WarnningList.actionStart(getContext(),checkStatus,riskpointId);
                break;
            case R.id.tvRegisterHiddenDanger:
                //登记隐患
                HiddendangerUnSubmit.actionStart(getContext(),"",riskpointId,0);
                break;
            case R.id.ivCamera:
                //选取图片
                PhotoPickBottomDialog pickBottomDialog=new PhotoPickBottomDialog();
                pickBottomDialog.setClicklistener(new PhotoPickBottomDialog.ClickListenerInterface() {
                    @Override
                    public void takePhoto() {
                        //拍照并剪裁
                        PictureSelector.create(RiskPointDetail.this)
                                .openGallery(PictureMimeType.ofImage())
                                .selectionMode(PictureConfig.SINGLE)
                                .isCamera(true)
                                .compressQuality(100)
                                .compress(true)
                                .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                .forResult(PictureConfig.REQUEST_CAMERA);
                    }

                    @Override
                    public void selectFromAlbum() {
                        PictureSelector.create(RiskPointDetail.this)
                                .openGallery(PictureMimeType.ofImage())
                                .selectionMode(PictureConfig.SINGLE)
                                .isCamera(false)
                                .compressQuality(100)
                                .compress(true)
                                .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    }
                });
                pickBottomDialog.show(getSupportFragmentManager());
                break;
        }
    }





    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.risk_point_detail;
    }

    @Override
    protected void initView() {
        setTitleText("风险点详情");
        checkStatus=getIntent().getStringExtra("checkStatus");
        riskpointId=getIntent().getStringExtra("riskpointId");
        riskLevel=getIntent().getIntExtra("riskLevel",0);
        tabLayout=findViewById(R.id.tabLayout);
        _barTvRight=findViewById(R.id._barTvRight);
        _barBack=findViewById(R.id._barBack);
        tvWarnning=findViewById(R.id.tvWarnning);
        viewPager=findViewById(R.id.viewPager);
        llWarnning=findViewById(R.id.llWarnning);
        scrollView=findViewById(R.id.scrollView);
        tvImmediateCheck=findViewById(R.id.tvImmediateCheck);
        tvMore=findViewById(R.id.tvMore);
        tvRiskPointTitle=findViewById(R.id.tvRiskPointTitle);
        tvRegisterHiddenDanger=findViewById(R.id.tvRegisterHiddenDanger);
        ivCamera=findViewById(R.id.ivCamera);
        tvDepartName=findViewById(R.id.tvDepartName);
        ivStatus=findViewById(R.id.ivStatus);
        ivLevel=findViewById(R.id.ivLevel);
        ivRiskPoint=findViewById(R.id.ivRiskPoint);
        tvMore.setOnClickListener(this::onClick);
        tvImmediateCheck.setOnClickListener(this::onClick);
        _barBack.setOnClickListener(this::onClick);
        _barTvRight.setOnClickListener(this::onClick);
        tvRegisterHiddenDanger.setOnClickListener(this::onClick);
        ivCamera.setOnClickListener(this::onClick);

        mTitleList=new ArrayList<>();
        mTitleList.add("基本信息");
        mTitleList.add("检查日志");
        mTitleList.add("作业指导书");
        mTitleList.add("风险");
        mTitleList.add("隐患");
        mTitleList.add("安全检查表");
        mTitleList.add("现场人员");
        fragmentList=new ArrayList<>();

        getData();
        getUserInfo();
    }

    public  void getUserInfo() {
        new HttpRequest(RiskPointDetail.this).doGet(UrlConstants.userInfoqueryPersonage, null,new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), UserInfoModel.class);
                        if (obj instanceof UserInfoModel) {
                            UserInfoModel model = (UserInfoModel) obj;
                            UserData.create(RiskPointDetail.this).saveUserData(model.getResult());
                        }
                    }else {
                        Toast.makeText(RiskPointDetail.this,message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

    //适配器
    public class MainAdapter extends FragmentPagerAdapter {

        public MainAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mTitleList.size();
        }

        //获取标题
        @Override
        public CharSequence getPageTitle(int position) {
            return mTitleList.get(position);
        }
    }

    @Override
    protected void initData() { }

    @Override
    protected int getTitleBarType() {
        return TITLEBAR_NULL;
    }

    public void getData(){
        new HttpRequest(RiskPointDetail.this).doGet(UrlConstants.getRiskPointDetail+riskpointId, "", new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    int  code = jsonObject.getInt("code");
                    if (code==200) {
                        Object obj = JsonUtils.fromJson(result.toString(), RiskPointDetailModel.class);
                        if (obj instanceof RiskPointDetailModel) {
                             riskPointDetail=(RiskPointDetailModel) obj;
                             setView();
                            fragmentList.add(new RiskDetailBasicInfoFragment(viewPager,riskPointDetail));
                            fragmentList.add(new RiskDetailCheckLogFragment(viewPager,riskpointId,riskLevel));
                            fragmentList.add(new RiskDetailInstructionFragment(viewPager,riskpointId));
                            fragmentList.add(new RiskDetailRiskFragment(viewPager,riskpointId));
                            fragmentList.add(new RiskDetailHiddendangerFragment(viewPager,riskpointId));
                            fragmentList.add(new RiskDetailTableFragment(viewPager,riskpointId));
                            fragmentList.add(new RiskDetailPersonFragment(viewPager,riskpointId));

                            adapter=new MainAdapter(getSupportFragmentManager());
                            tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
                            tabLayout.setupWithViewPager(viewPager);
                            viewPager.setAdapter(adapter);
                            viewPager.resetHeight(0);
                            tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                                @Override
                                public void onTabSelected(TabLayout.Tab tab) {
                                    viewPager.resetHeight(tab.getPosition());
                                    viewPager.setCurrentItem(tab.getPosition());
                                }

                                @Override
                                public void onTabUnselected(TabLayout.Tab tab) { }

                                @Override
                                public void onTabReselected(TabLayout.Tab tab) { }
                            });
                        }
                    }else {
                        Toast.makeText(RiskPointDetail.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }


    public void setView(){
        Glide.with(this).load(riskPointDetail.getResult().getRiskPointImg()).
                placeholder(R.mipmap.icon_home_banner).
                into(ivRiskPoint);
        tvRiskPointTitle.setText(riskPointDetail.getResult().getRiskPointName());
        tvDepartName.setText(riskPointDetail.getResult().getDepartName());
        switch (riskPointDetail.getResult().getIsOutOfControl()){
            case 0:
                ivStatus.setImageResource(R.mipmap.icon_shield);
                llWarnning.setVisibility(View.GONE);
                break;
            case 1:
                ivStatus.setImageResource(R.mipmap.icon_fire);
                llWarnning.setVisibility(View.VISIBLE);
                break;
        }

        if (riskPointDetail.getResult().getRiskLevel()!=null){
            switch (riskPointDetail.getResult().getRiskLevel()){
                case 1:
                    ivLevel.setImageResource(R.mipmap.icon_shan_red_circle);
                    break;
                case 2:
                    ivLevel.setImageResource(R.mipmap.icon_shan_orange_circle);
                    break;
                case 3:
                    ivLevel.setImageResource(R.mipmap.icon_shan_yellow_circle);
                    break;
                case 4:
                    ivLevel.setImageResource(R.mipmap.icon_shan_blue_circle);
                    break;
            }
        }
    }

    private String path="";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            if (requestCode==PictureConfig.CHOOSE_REQUEST||requestCode==PictureConfig.REQUEST_CAMERA) {
                // 结果回调 获取oss  token
                List<LocalMedia> cameraList = PictureSelector.obtainMultipleResult(data);
                    if (cameraList.size()>0){
                        path=cameraList.get(0).getRealPath();
                        uploadImg(path);
                    }
            }
        }
    }

    public void uploadImg(String path){
        new HttpRequest(RiskPointDetail.this).doUploadFile(UrlConstants.commonupload, "", "file", new File(path), new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model=(BaseModel) obj;
                            submitDetail(model.getMessage());
                        }else {
                            ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, message, 1);
                            toastUtil.show();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

    public void submitDetail(String riskImg){
        Map jsonObject=new HashMap();
        jsonObject.put("riskImg",riskImg);
        jsonObject.put("riskId",riskpointId);
        new HttpRequest(this).doGet(UrlConstants.risk_updateRiskImg, null,jsonObject, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        //上传成功
                        Glide.with(RiskPointDetail.this).load(path).
                                placeholder(R.mipmap.icon_home_banner)
                                .into(ivRiskPoint);
                    }else {
                        Toast.makeText(RiskPointDetail.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.e("aaaa",msg);
            }
        });
    }
}